package com.qyhl.module_activities.act.signup;

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.view.MotionEventCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qyhl.module_activities.R;
import com.qyhl.module_activities.R2;
import com.qyhl.module_activities.utils.ViewUtils;
import com.qyhl.module_activities.utils.inter.ActCheckBoxCallBack;
import com.qyhl.module_activities.utils.inter.ActImageCallBack;
import com.qyhl.module_activities.utils.inter.ActPopupCallBack;
import com.qyhl.module_activities.utils.inter.ActRadioButtonCallBack;
import com.qyhl.module_activities.utils.inter.ActVideoCallBack;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.constant.ErrorCode;
import com.qyhl.webtv.commonlib.constant.PathConfigConstant;
import com.qyhl.webtv.commonlib.entity.UpTokenBean;
import com.qyhl.webtv.commonlib.entity.act.ActivityViewBean;
import com.qyhl.webtv.commonlib.entity.act.PlayerResultBean;
import com.qyhl.webtv.commonlib.entity.act.UploadBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.qiniu.QiniuUpload;
import com.qyhl.webtv.commonlib.utils.qiniu.UploadResultListener;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.imagebrowser.MNImageBrowser;
import com.weavey.loading.lib.LoadingLayout;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;

import static com.qyhl.webtv.commonlib.utils.view.video.emptyvideo.EmptyControlVideoActivity.IntentKey_VideoCover;
import static com.qyhl.webtv.commonlib.utils.view.video.emptyvideo.EmptyControlVideoActivity.IntentKey_VideoUrl;

/**
 * 报名活动
 *
 * @author helin
 */
@Route(path = ARouterPathConstant.ACT_SIGN_UP)
public class SignUpActActivity extends BaseActivity implements ActPopupCallBack, SignUpActContract.SignUpActView
        , ActRadioButtonCallBack, ActCheckBoxCallBack, ActImageCallBack, ActVideoCallBack {

    /**
     * 图片多选
     */
    public static final int CHOOSE_REQUEST = 188;
    /**
     * 图片单选
     */
    public static final int CHOOSE_SINGLE_REQUEST = 189;

    /**
     * 视频选择
     */
    public static final int CHOOSE_VIDEO = 191;


    @BindView(R2.id.room_view)
    LinearLayout mRoomView;
    @BindView(R2.id.nestedscrollview)
    NestedScrollView nestedscrollview;

    @BindView(R2.id.act_view_loading)
    LoadingLayout mLoadingLayout;

    @BindView(R2.id.sign_act_phone_edit)
    EditText sign_act_phone_edit;

    @BindView(R2.id.video_layout)
    RelativeLayout videoLayout;

    @BindView(R2.id.video_tips)
    TextView videoTips;
    /**
     * 视频选择
     */
    @BindView(R2.id.act_sign_video)
    ImageView mSignVideo;


    @BindView(R2.id.act_video_del)
    ImageView mImageDel;

    @BindView(R2.id.video_work_name)
    EditText workNameEt;

    @BindView(R2.id.video_work_desc)
    EditText workDescEt;

    /**
     * 活动Id
     */
    @Autowired(name = "actId")
    int mActId;
    private SignUpActPresenter mPresenter;
    /**
     * 自定义控件
     */
    private List<ActivityViewBean> mActivityView;
    /**
     * 多选控件数据
     */
    private SparseArray<List<String>> mCheckData = new SparseArray<List<String>>();

    /**
     * 当前操作的View
     */
    private int mIndex;
    /**
     * 单选控件数据
     */
    private SparseArray<String> mRadioDatas = new SparseArray<>();
    /**
     * 下拉控件数据
     */
    private SparseArray<String> mPopupDatas = new SparseArray<>();
    /**
     * 图片选择控件数据
     */
    private SparseArray<String> mImageViewDatas = new SparseArray<>();

    /**
     * 图片数据
     */
    private List<LocalMedia> selectedList = new ArrayList<>();

    /**
     * 图片选择Adapter
     */
    private RecyclerViewAdatper mImageAdapter;

    /**
     * 空数据
     */
    private LocalMedia addMde;
    /**
     * 图片上传token
     */
    private UpTokenBean mImageToken;
    /**
     * 用户填写报名信息
     */
    private List<PlayerResultBean> mResultDatas;
    /**
     * 用户上传文件信息
     */
    private List<UploadBean> mUploadDatas;
    /**
     * 视频文件地址
     */
    private String mVideoPath;
    /**
     * 视频封面地址
     */
    private String mVideoCoverPath;
    /**
     * 展示View的Id
     */
    public int mShowId;

    /**
     * 报名图View的Id
     */
    private int mApplyImageId = 0;

    /**
     * 视频名称弹框
     */
    private ChangeNameDialog dialog;

    private String workName;
    private String workDescription;
    private String videoWorkName;
    private String videoWorkDesc;
    private String username;

    private String videoViewText;
    private Integer videoViewId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.act_activity_sign_up_act;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new SignUpActPresenter(this);
        initView();
    }

    @Override
    protected void setListener() {

    }

    /**
     * 初始化
     */
    private void initView() {
        //添加最有一个图片
        addMde = new LocalMedia();
        addMde.setPath("1");
        selectedList.add(addMde);

        mLoadingLayout.setStatus(LoadingLayout.Loading);
        mPresenter.getActViews(mActId);
        mPresenter.getToken(false);
        mLoadingLayout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View view) {
                mLoadingLayout.setStatus(LoadingLayout.Loading);
                mPresenter.getActViews(mActId);
            }
        });
    }


    @Override
    public void onError(String string) {
        errorLoad(string, mLoadingLayout);
    }

    @Override
    public void checkError(String msg) {
        showToast(msg, INFO);
    }


    @Override
    public void onEmpty() {
        emptyLoad(mLoadingLayout);
    }

    /**
     * 获取自定义控件
     *
     * @param data
     */
    @Override
    public void onSuccess(List<ActivityViewBean> data) {
        mLoadingLayout.setStatus(LoadingLayout.Success);

        mActivityView = data;
        if (mActivityView != null && !mActivityView.isEmpty()) {
            mRoomView.setVisibility(View.VISIBLE);
        }
        for (int i = 0; i < data.size(); i++) {
            ActivityViewBean dataView = data.get(i);
            //展示Viw的Id
            if (dataView.getActivityView().getIsShow() == 1) {
                mShowId = dataView.getActivityView().getId();
            }
            //报名图的View
            if (dataView.getActivityView().getIsShow() == 2) {
                mApplyImageId = dataView.getActivityView().getId();
            }
            View view = null;
            switch (dataView.getTypeName()) {
                case "radio":
                    //单选框
                    view = ViewUtils.createRadio(this, mRoomView, dataView.getActivityView().getViewText(), dataView.getViewOptions(), dataView.getActivityView().getIsRequired(), i, dataView.getActivityView().getDescription(), this);
                    break;
                case "checkbox"://---
                    view = ViewUtils.createCheckBox(this, mRoomView, dataView.getActivityView().getViewText(), dataView.getViewOptions(), dataView.getActivityView().getIsRequired(), i, dataView.getActivityView().getDescription(), this);
                    //多选框
                    break;
                case "input":
                    //单行输入框
                    view = ViewUtils.createInputView(this, mRoomView, dataView.getActivityView().getViewText(), dataView.getActivityView().getDescription(), dataView.getActivityView().getIsRequired(), i);
                    break;
                case "textarea"://---
                    view = ViewUtils.createMultiInputView(this, mRoomView, dataView.getActivityView().getViewText(), dataView.getActivityView().getDescription(), dataView.getActivityView().getIsRequired(), i);
                    //多行输入框
                    break;
                case "image":
                    //图片选择
                    view = ViewUtils.createImageView(this, mRoomView, dataView.getActivityView().getViewText(), dataView.getActivityView().getDescription(), dataView.getActivityView().getIsRequired(), i, this);
                    break;
                case "datetime":
                    //时间
                    view = ViewUtils.createDateTimeView(this, mRoomView, dataView.getActivityView().getViewText(), dataView.getActivityView().getIsRequired(), i);
                    break;
                case "image_works":
                    //图片作品
                    view = ViewUtils.createImageWorkView(this, mRoomView, dataView.getActivityView().getViewText(), dataView.getActivityView().getDescription(), dataView.getActivityView().getIsRequired(), mImageAdapter = new RecyclerViewAdatper(), i);
                    break;
                case "video":
//                    view = ViewUtils.createVideoView(this, mRoomView, dataView.getActivityView().getViewText(), dataView.getActivityView().getDescription(), dataView.getActivityView().getIsRequired(), i, this);
                    videoLayout.setVisibility(View.VISIBLE);
                    videoTips.setText(dataView.getActivityView().getDescription());
                    break;
                case "select":
                    //下拉
                    view = ViewUtils.createPopupView(this, mRoomView, dataView.getActivityView().getViewText(), dataView.getViewOptions(), dataView.getActivityView().getIsRequired(), i, this);
                    break;
                default:
                    break;
            }
            if (view != null) {
                mRoomView.addView(view);
            }
        }
    }

    @Override
    public void getTokenSuccess(UpTokenBean data, boolean isUpload) {
        mImageToken = data;
        if (isUpload) {
            checkData();
        }
    }

    @Override
    public void getTokenError(boolean isUpload) {
        if (isUpload) {
            showToast("上传失败！", 4);
        }
    }

    /**
     * 上传失败
     *
     * @param msg
     */
    @Override
    public void uplaodError(int code, String msg) {
        //报名失败
        dismissLoading();
        switch (code) {
            case ErrorCode.JOIN_ACTIVITY_ERROR:
                showToast("活动未开始", INFO);
                break;
            case ErrorCode.JOIN_ACTIVITY_ERROR3:
                showToast("活动已结束", INFO);
                break;
            case ErrorCode.JOIN_ACTIVITY_ERROR4:
                showToast("报名已结束", INFO);
                break;
            case ErrorCode.SGIN_ACTIVITY:
            case ErrorCode.SGIN_ACTIVITY_REVIEW:
                showToast("您已报名", INFO);
                break;
            default:
                showToast(msg, INFO);
        }
    }

    /**
     * 报名成功
     */
    @Override
    public void signSuccess() {
        ActionLogUtils.getInstance().onEvent(ActionConstant.SIGN_ACTIVITY);
        //报名成功
        dismissLoading();
        showToast("报名成功", INFO);
        setResult(666);
        finish();
    }

    /**
     * 单选回调
     *
     * @param index
     * @param text
     * @param isCheck
     */
    @Override
    public void onRadioCheck(int index, String text, boolean isCheck) {
        mRadioDatas.put(index, text);
    }

    /**
     * 多选回调
     *
     * @param index
     * @param text
     * @param isCheck
     * @return
     */
    @Override
    public boolean onCheck(int index, String text, boolean isCheck) {
        if (mCheckData.get(index) != null) {
            //存在
            if (isCheck) {
                //添加item
                List<String> list = mCheckData.get(index);
//                ActivityViewBean view = mActivityView.get(index);
//                Integer maxNumber = view.getActivityView().getSort();
//                //最多选择个数
//                if (list.size() == maxNumber) {
//                    showToast("最多只能选择" + maxNumber + "个", SUCCESS);
//                    return false;
//                } else {
//                    list.add(text);
//                }
                list.add(text);
            } else {
                //取消选择item
                List<String> list = mCheckData.get(index);
                list.remove(text);
            }
        } else {
            //不存在
            List<String> data = new ArrayList<String>();
            data.add(text);
            mCheckData.put(index, data);
        }
        return true;
    }

    @Override
    public void choiceImage(int index) {
        //选择图片
        mIndex = index;
        chooseMenu(CHOOSE_SINGLE_REQUEST);
    }

    @Override
    public void deleteImage(int index) {
        //删除图片
        mIndex = index;
        View view = mRoomView.getChildAt(index);
        ImageView image = (ImageView) view.findViewById(R.id.act_sign_image);
        ImageView imageDel = (ImageView) view.findViewById(R.id.act_sign_del);
        imageDel.setVisibility(View.GONE);
        image.setImageResource(R.drawable.add_image);
        mImageViewDatas.remove(index);
    }

    /**
     * 图片多选
     */
    private void chooseImage() {
        PictureSelector.create(SignUpActActivity.this)
                //仅图片
                .openGallery(PictureMimeType.ofImage())
                //每行显示4张
                .imageSpanCount(4)
                .maxSelectNum(9)
                .selectionMode(PictureConfig.SINGLE)
                //允许使用相机
                .isCamera(true)
                //允许预览图片
                .previewImage(true)
                .isZoomAnim(true)
                .compress(true)
                .selectionMedia(selectedList)
                // 小于100kb的图片不压缩
                .minimumCompressSize(100)
                .forResult(CHOOSE_REQUEST);
    }


    /**
     * 选图片
     */
    private void chooseMenu(int result) {
        PictureSelector.create(SignUpActActivity.this)
                //仅图片
                .openGallery(PictureMimeType.ofImage())
                //每行显示4张
                .imageSpanCount(4)
                .selectionMode(PictureConfig.SINGLE)
                //允许使用相机
                .isCamera(true)
                //允许预览图片
                .previewImage(true)
                .isZoomAnim(true)
                .compress(true)
                // 小于100kb的图片不压缩
                .minimumCompressSize(100)
                .forResult(result);
    }

    /**
     * 修改图片控件数据
     *
     * @param path
     */
    private void setImageView(String path) {
        View view = mRoomView.getChildAt(mIndex);
        ImageView image = (ImageView) view.findViewById(R.id.act_sign_image);
        ImageView imageDel = (ImageView) view.findViewById(R.id.act_sign_del);
        //加载本地图片
        Glide.with(this)
                .load(path)
                .into(image);
        imageDel.setVisibility(View.VISIBLE);
    }

    private void setVideoView(String path) {
        View view = mRoomView.getChildAt(mIndex);
        ImageView image = (ImageView) view.findViewById(R.id.act_sign_video);
        ImageView imageDel = (ImageView) view.findViewById(R.id.act_sign_del);

        Glide.with(this)
                .load(path)
                .into(image);

        imageDel.setVisibility(View.VISIBLE);
    }


    /**
     * 检查报名数据
     */
    private void checkData() {
        if (!CommonUtils.getInstance().getUserCheck().equals("1") && CommonUtils.getInstance().getSite() == 217) {
            showToast("用户信息审核中，暂时无法使用该功能！", INFO);
            return;
        }
        videoWorkName = workNameEt.getText().toString();
        if (TextUtils.isEmpty(videoWorkName)) {
            showToast("请输入作品标题", INFO);
            return;
        }

        videoWorkDesc = workDescEt.getText().toString();

        username = sign_act_phone_edit.getText().toString();
        if (TextUtils.isEmpty(username)) {
            showToast("手机号码为必填项", INFO);
            return;
        }
        List<PlayerResultBean> resultDatas = new ArrayList<>();
        List<UploadBean> uploadBeans = new ArrayList<>();
        for (int i = 0; i < mActivityView.size(); i++) {
            ActivityViewBean dataView = mActivityView.get(i);
            View view = mRoomView.getChildAt(i);
            PlayerResultBean playerResultBean = new PlayerResultBean();
            if (dataView.getActivityView().getId() == mShowId) {
                playerResultBean.setIsShow(1);
            } else {
                playerResultBean.setIsShow(0);
            }
            switch (dataView.getTypeName()) {
                case "radio": {
                    //单选框
                    Integer isRe = dataView.getActivityView().getIsRequired();
                    String str = mRadioDatas.get(i);
                    if (StringUtils.isEmpty(str)) {
                        if (1 == isRe) {
                            showToast(dataView.getActivityView().getViewText() + "为必填项", INFO);
                            return;
                        }
                        continue;
                    }
                    playerResultBean.setType(dataView.getTypeName());
                    playerResultBean.setResultText(str);
                    playerResultBean.setViewId(dataView.getActivityView().getId());
                    playerResultBean.setViewText(dataView.getActivityView().getViewText());
                }
                break;
                case "select": {
                    //下拉框
//                    Integer isRe = dataView.getActivityView().getIsRequired();
                    String str = mPopupDatas.get(i);
//                    if (StringUtils.isEmpty(str)) {
//                        if (1 == isRe) {
//                            showToast(dataView.getActivityView().getViewText() + "为必填项", INFO);
//                            return;
//                        }
//                        continue;
//                    }
                    playerResultBean.setType(dataView.getTypeName());
                    playerResultBean.setResultText(str);
                    playerResultBean.setViewId(dataView.getActivityView().getId());
                    playerResultBean.setViewText(dataView.getActivityView().getViewText());
                }
                break;
                case "checkbox":
                    //多选框
                {
                    Integer isRe = dataView.getActivityView().getIsRequired();
                    List<String> checks = mCheckData.get(i);
                    if (checks == null || checks.size() == 0) {
                        if (isRe == 1) {
                            showToast(dataView.getActivityView().getViewText() + "为必填项", INFO);
                            return;
                        }
                        continue;
                    }
                    playerResultBean.setType(dataView.getTypeName());
                    playerResultBean.setResultText(mPresenter.getOptionStr(checks));
                    playerResultBean.setViewText(dataView.getActivityView().getViewText());
                    playerResultBean.setViewId(dataView.getActivityView().getId());
                    playerResultBean.setOptionsIds(mPresenter.getOptioinIds(checks, dataView.getViewOptions()));
                }
                break;
                case "video": {
                    Integer isRe = dataView.getActivityView().getIsRequired();
                    if (StringUtils.isEmpty(mVideoPath)) {
                        if (isRe == 1) {
                            showToast(dataView.getActivityView().getViewText() + "为必填项", INFO);
                            return;
                        }
                        continue;
                    }
                    UploadBean videoBean = new UploadBean();
                    videoBean.setType(3);
                    videoBean.setPath(mVideoPath);
                    videoBean.setPostion(0);
                    uploadBeans.add(videoBean);

                    UploadBean videoCoverBean = new UploadBean();
                    videoCoverBean.setType(4);
                    videoCoverBean.setPath(mVideoCoverPath);
                    videoCoverBean.setPostion(0);
                    uploadBeans.add(videoCoverBean);
                }
                break;
                case "input":
                    //单行输入框
                {
                    Integer isRe = dataView.getActivityView().getIsRequired();
                    EditText ed = (EditText) view.findViewById(R.id.sign_act_edit);
                    String inputStr = ed.getText().toString();
                    if (StringUtils.isEmpty(inputStr)) {
                        if (isRe == 1) {
                            showToast(dataView.getActivityView().getViewText() + "为必填项", INFO);
                            return;
                        }
                        continue;
                    }

                    playerResultBean.setType(dataView.getTypeName());
                    playerResultBean.setResultText(inputStr);
                    playerResultBean.setViewId(dataView.getActivityView().getId());
                    playerResultBean.setViewText(dataView.getActivityView().getViewText());
                }
                break;
                case "textarea":
                    //多行输入框
                {
                    Integer isRe = dataView.getActivityView().getIsRequired();
                    EditText ed = (EditText) view.findViewById(R.id.sign_act_multi_edit);
                    String inputStr = ed.getText().toString();
                    if (StringUtils.isEmpty(inputStr)) {
                        if (isRe == 1) {
                            showToast(dataView.getActivityView().getViewText() + "为必填项", INFO);
                            return;
                        }
                        continue;
                    }
                    playerResultBean.setType(dataView.getTypeName());
                    playerResultBean.setResultText(inputStr);
                    playerResultBean.setViewId(dataView.getActivityView().getId());
                    playerResultBean.setViewText(dataView.getActivityView().getViewText());
                }
                break;
                case "image":
                    //图片选择
                    Integer isRe = dataView.getActivityView().getIsRequired();
                    String path = mImageViewDatas.get(i);
                    if (StringUtils.isEmpty(path)) {
                        if (isRe == 1) {
                            showToast(dataView.getActivityView().getViewText() + "为必填项", INFO);
                            return;
                        }
                        continue;
                    }
                    UploadBean uploadBean = new UploadBean();
                    uploadBean.setType(1);
                    uploadBean.setPath(path);
                    uploadBean.setPostion(i);
                    uploadBean.setViewId(dataView.getActivityView().getId());
                    uploadBean.setViewText(dataView.getActivityView().getViewText());
                    uploadBeans.add(uploadBean);
                    break;
                case "datetime": {
                    Integer timeRequired = dataView.getActivityView().getIsRequired();
                    TextView dateTime = (TextView) view.findViewById(R.id.text_time);
                    String inputStr = dateTime.getText().toString();
                    if (StringUtils.isEmpty(inputStr)) {
                        if (timeRequired == 1) {
                            showToast(dataView.getActivityView().getViewText() + "为必填项", INFO);
                            return;
                        }
                        continue;
                    }
                    playerResultBean.setType(dataView.getTypeName());
                    playerResultBean.setResultText(inputStr);
                    playerResultBean.setViewId(dataView.getActivityView().getId());
                    playerResultBean.setViewText(dataView.getActivityView().getViewText());
                }
                break;
                case "image_works": {
                    Integer timeRequired = dataView.getActivityView().getIsRequired();
                    EditText pic_work_name_text = (EditText) view.findViewById(R.id.pic_work_name_text);
                    EditText pic_work_introduce_text = (EditText) view.findViewById(R.id.pic_work_introduce_text);
                    workName = pic_work_name_text.getText().toString();
                    workDescription = pic_work_introduce_text.getText().toString();
                    if (timeRequired == 1) {
                        if (selectedList.size() <= 1) {
                            showToast(dataView.getActivityView().getViewText() + "为必填项", INFO);
                            return;
                        }
                        if (TextUtils.isEmpty(workName)) {
                            showToast(dataView.getActivityView().getViewText() + "作品集名为必填项", INFO);
                            return;
                        }
                        if (TextUtils.isEmpty(workDescription)) {
                            workDescription = "";
                        }
                    }
                }
                break;
                default:
                    playerResultBean.setType("other");
                    break;
            }
            if (playerResultBean.getViewId() != 0) {
                resultDatas.add(playerResultBean);
            }
        }
        mResultDatas = resultDatas;
        mUploadDatas = uploadBeans;
        signUp(mResultDatas, mUploadDatas);
    }

    @Override
    public void checkSuccess() {

    }

    @Override
    public int getApplyViewId() {
        return mApplyImageId;
    }


    /**
     * 报名活动
     *
     * @param results
     */
    private void signUp(final List<PlayerResultBean> results, List<UploadBean> uploadBeans) {

        showHorizontalSimpleLoading("uploadImage");
        //图片作品
        for (int i = 0; i < selectedList.size() - 1; i++) {
            UploadBean uploadBean = new UploadBean();
            uploadBean.setType(2);
            uploadBean.setPath(selectedList.get(i).getCompressPath());
            uploadBean.setPostion(0);
            uploadBeans.add(uploadBean);
        }
        //视频
        if (!StringUtils.isEmpty(mVideoPath)) {
            UploadBean videoBean = new UploadBean();
            videoBean.setType(3);
            videoBean.setPath(mVideoPath);
            videoBean.setPostion(0);
            uploadBeans.add(videoBean);
        }
        //视频封面
        if (!StringUtils.isEmpty(mVideoCoverPath)) {
            UploadBean videoCoverBean = new UploadBean();
            videoCoverBean.setType(4);
            videoCoverBean.setPath(mVideoCoverPath);
            videoCoverBean.setPostion(0);
            uploadBeans.add(videoCoverBean);
        }
        if (uploadBeans.isEmpty()) {
            mPresenter.combinationData(results, uploadBeans, mActId, workName, workDescription, username, videoWorkName, TextUtils.isEmpty(videoWorkDesc) ? "" : videoWorkDesc);
        } else {
            if (mImageToken == null) {
                mPresenter.getToken(true);
                return;
            }
            QiniuUpload.getQiniuUpload().UploadFiles(uploadBeans, mImageToken.getUptoken(), mImageToken.getPrefix(), new UploadResultListener() {
                @Override
                public void uplaodError() {
                    dismissLoading();
                    showToast("上传图片出错", INFO);
                }

                @Override
                public void uploadSuccess(List<UploadBean> files) {
                    mPresenter.combinationData(results, files, mActId, workName, workDescription, username, videoWorkName, TextUtils.isEmpty(videoWorkDesc) ? "" : videoWorkDesc);
                }

                @Override
                public void uploadPre(double percent) {
                    setPro((int) percent);
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> resultList;
        switch (requestCode) {
            case CHOOSE_SINGLE_REQUEST:
                resultList = PictureSelector.obtainMultipleResult(data);
                if (resultList.size() != 0) {
                    String path = resultList.get(0).getCompressPath();
                    mImageViewDatas.put(mIndex, path);
                    //设置view
                    setImageView(path);
                }
                break;
            case CHOOSE_REQUEST:
                resultList = PictureSelector.obtainMultipleResult(data);
                if (resultList != null && resultList.size() > 0) {
                    selectedList.clear();
                    selectedList.addAll(resultList);
                }
                selectedList.add(addMde);
                mImageAdapter.notifyDataSetChanged();
                break;
            case CHOOSE_VIDEO: {
                //视频选择
                List<LocalMedia> pic = PictureSelector.obtainMultipleResult(data);
                // TODO 处理视频
                if (pic != null && pic.size() > 0) {
                    //视频路径
                    String path = pic.get(0).getPath();
                    mVideoPath = path;
                    getPicture(path);
                    Glide.with(SignUpActActivity.this)
                            .load(mVideoCoverPath)
                            .into(mSignVideo);
                    mImageDel.setVisibility(View.VISIBLE);
                    dismissLoading();
                }
            }

            break;
            default:
                break;
        }
    }

//    /**
//     * 压缩视频
//     */
//    private void compressVideo(String path) {
//        showLoading("压缩视频中...");
//        //获取视频封面
//        getPicture(path);
//        String cacheUrl = getExternalCacheDir().getPath();
//        String fileName = UUID.randomUUID().toString();
//        final String outPath = cacheUrl + "/" + fileName + ".mp4";
//
//        VideoCompress.compressVideo(path, outPath, new VideoCompressCallBack() {
//            @Override
//            public void onSuccess() {
//                mVideoPath = outPath;
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Glide.with(SignUpActActivity.this)
//                                .load(mVideoCoverPath)
//                                .into(mSignVideo);
//                        mImageDel.setVisibility(View.VISIBLE);
//                        dismissLoading();
//                    }
//                });
//            }
//
//            @Override
//            public void onError() {
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        dismissLoading();
//                        showToast("压缩失败", INFO);
//                    }
//                });
//            }
//
//            @Override
//            public void onPre(int pre) {
//
//            }
//        });
//    }

    /**
     * 获取视频封面图
     */
    public void getPicture(String path) {
        File file = new File(path);
        //判断对象是否存在，不存在的话给出Toast提示
        if (file.exists()) {
            //提供统一的接口用于从一个输入媒体中取得帧和元数据
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(path);
            Bitmap bitmap = retriever.getFrameAtTime();
            CommonUtils.getInstance().getSite();
            String dirpath = Environment.getExternalStorageDirectory().getPath() + PathConfigConstant.Pic;
            File dir = new File(dirpath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String name = UUID.randomUUID().toString() + ".png";
            mVideoCoverPath = Environment.getExternalStorageDirectory().getPath() + PathConfigConstant.Pic + File.separator + name;
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(mVideoCoverPath);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
                showToast("生成封面图失败", INFO);
            }
        } else {
            showToast("视频路径不存在", INFO);
        }
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R2.id.act_sign_video, R2.id.back, R2.id.add_commit, R2.id.act_video_del})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.back) {
            finish();

        } else if (i == R.id.add_commit) {//提交报名
            checkData();

        } else if (i == R.id.act_video_del) {
            mSignVideo.setImageResource(R.drawable.scoop_add_video);
            mVideoCoverPath = "";
            mVideoPath = "";
            mImageDel.setVisibility(View.GONE);

        } else if (i == R.id.act_sign_video) {
            chooseVideo();
        }
    }

    /**
     * 选择视频
     */
    private void chooseVideo() {
        PictureSelector.create(SignUpActActivity.this)
                .openGallery(PictureMimeType.ofVideo())
                .imageSpanCount(4)
                .previewVideo(true)
                .maxSelectNum(1)
                .selectionMode(PictureConfig.SINGLE)
                .isCamera(true)
                .isZoomAnim(true)
                .compress(true)
                .videoMaxSecond(180)
                .videoMinSecond(2)
                .recordVideoSecond(180)
                .videoQuality(1)
                .forResult(CHOOSE_VIDEO);
    }

    @Override
    public void onPopupCheck(int index, String text) {
        mPopupDatas.put(index, text);
    }

    @Override
    public void choiceVideo(int index) {
        mIndex = index;
        if (StringUtils.isNotEmpty(mVideoCoverPath)) {
            Bundle bundle = new Bundle();
            bundle.putString(IntentKey_VideoUrl, mVideoPath);
            bundle.putString(IntentKey_VideoCover, mVideoCoverPath);

            RouterManager.router(ARouterPathConstant.VIDEO_EMPTY_CONTROL, bundle);
        } else {
            chooseVideo();
        }
    }

    @Override
    public void deleteVideo(int index) {
        //删除图片
        mIndex = index;
        View view = mRoomView.getChildAt(index);
        ImageView image = (ImageView) view.findViewById(R.id.act_sign_video);
        ImageView imageDel = (ImageView) view.findViewById(R.id.act_sign_del);
        imageDel.setVisibility(View.GONE);
        image.setImageResource(R.drawable.active_applylist_button_addvideo);

        mVideoCoverPath = "";
        mVideoPath = "";
    }


    /**
     * RecyclerViewAdatper
     */
    public class RecyclerViewAdatper extends RecyclerView.Adapter<SignUpActActivity.ViewHolder> {

        RecyclerViewAdatper() {
        }

        @Override
        public SignUpActActivity.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.act_item_content_img_list, parent, false);
            return new SignUpActActivity.ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final SignUpActActivity.ViewHolder holder, final int position) {
            if (selectedList.get(position).getPath().endsWith("1")) {
                holder.deleteView.setVisibility(View.GONE);
                holder.handleView.setImageResource(R.drawable.icon_add_iamge);
                holder.handleView.setOnTouchListener(null);
            } else {
                holder.deleteView.setVisibility(View.VISIBLE);
                holder.deleteView.setTag(position);
                holder.deleteView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!selectedList.get(selectedList.size() - 1).getPath().endsWith("1")) {
                            selectedList.add(addMde);
                        }
                        int pos = (int) v.getTag();
                        selectedList.remove(pos);
                        mImageAdapter.notifyDataSetChanged();
                    }
                });
                if (position == selectedList.size() - 1) {
                    holder.handleView.setImageResource(R.drawable.icon_add_iamge);
                    holder.handleView.setOnTouchListener(null);
                } else {
                    Glide.with(SignUpActActivity.this).load(selectedList.get(position).getCompressPath()).into(holder.handleView);
                    holder.handleView.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
                                if (!selectedList.get(selectedList.size() - 1).getPath().endsWith("1")) {
                                    selectedList.add(addMde);
                                }
                            }
                            return false;
                        }
                    });
                }
            }
        }

        @Override
        public int getItemCount() {
            return selectedList.size();
        }
    }

    /**
     * ViewHolder
     */
    class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView handleView;
        public ImageView deleteView;

        public ViewHolder(View itemView) {
            super(itemView);
            handleView = (ImageView) itemView.findViewById(R.id.content_img);
            deleteView = (ImageView) itemView.findViewById(R.id.image_delete);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (selectedList.size() == 0 || !selectedList.get(selectedList.size() - 1).getPath().endsWith("1")) {
                        selectedList.add(addMde);
                    }
                    if (getLayoutPosition() == selectedList.size() - 1) {
                        //弹出选择菜单
                        selectedList.remove(selectedList.size() - 1);
                        chooseImage();
                    } else {

                        ArrayList<String> result = new ArrayList<>();
                        for (int i = 0; i < selectedList.size() - 1; i++) {
                            result.add(selectedList.get(i).getPath());
                        }
                        MNImageBrowser.showImageBrowser(SignUpActActivity.this, view, getLayoutPosition(), result);

                    }
                }
            });
        }


    }


}
